package com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.dao.ManualInvtDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.dao.ManualInvtSimpleDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.entity.ManualInvt;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.entity.ManualInvtSimple;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/11/11
 */
@Service
public class ManualInvtService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ManualService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource
    private ManualInvtDao manualInvtDao;
    @Resource
    private ManualInvtSimpleDao manualInvtSimpleDao;

    public String save(String invt) {
        if (StringUtils.isEmpty(invt)) return StringUtils.EMPTY;
        String invtText = SecurityUtil.decrypt3DES(token, invt);
        try {
            ManualInvt i = JSON.parseObject(invtText, ManualInvt.class);
            if (i == null) return StringUtils.EMPTY;

            i.addFields();
            ManualInvtSimple simple = i.buildManualInvtSimple();
            if (simple == null) return StringUtils.EMPTY;

            this.remove(i.getSeqNo());

            manualInvtDao.save(i);
            manualInvtSimpleDao.save(simple);
            return SecurityUtil.encrypt3DES(token, i.getInvt());
        } catch (Exception e) {
            LOGGER.error("保存加工贸易账册错误", e);
            return StringUtils.EMPTY;
        }
    }

    public String details(String seqNo) {
        ManualInvt invt = manualInvtDao.findBySeqNo(seqNo);
        if (invt == null) return StringUtils.EMPTY;
        return SecurityUtil.encrypt3DES(token, invt.getInvt());
    }

    public void remove(String seqNo) {
        manualInvtDao.delete(seqNo);
        manualInvtSimpleDao.delete(seqNo);
    }

    public boolean exists(String seqNo) {
        return manualInvtSimpleDao.exists(seqNo);
    }

    public String existsInvts(List<String> seqNos) {
        if (CollectionUtils.isEmpty(seqNos)) return StringUtils.EMPTY;
        List<List<String>> parts = Lists.partition(seqNos, 500);
        List<String> result = new ArrayList<>();
        parts.forEach(item -> result.addAll(manualInvtSimpleDao.exists(item)));
        return StringUtils.join(result, ",");
    }
}
